/**
 * 统一XR管理器
 * 合并所有WebXR相关功能，消除重复代码
 */

// 导入Three.js单例，确保整个应用中只有一个Three.js实例
import { THREE, XRControllerModelFactory, XRHandModelFactory } from './three-singleton.js';
import { HandTrackingManager } from '../interactions/HandTrackingManager.js';
import { CameraPermissionManager } from '../utils/CameraPermissionManager.js';
import webXRAudioSolution from './WebXRAudioSolution.js';
import { AudioPermissionManager } from './AudioPermissionManager.js';

export class UnifiedXRManager {
    constructor(renderer, scene, camera, options = {}) {
        this.renderer = renderer;
        this.scene = scene;
        this.camera = camera;
        
        // 配置选项
        this.options = {
            enableHandTracking: true,
            enableHapticFeedback: true,
            enableGestureRecognition: true,
            enableSpatialAudio: true,
            debugMode: false,
            ...options
        };
        
        // XR会话状态
        this.xrSession = null;
        this.isXRActive = false;
        this.xrMode = null;
        this.deviceType = null;
        
        // 控制器系统
        this.controllers = [];
        this.controllerGrips = [];
        this.controllerModelFactory = new XRControllerModelFactory();
        this.handModelFactory = new XRHandModelFactory();
        
        // 手部追踪管理器
        this.handTrackingManager = new HandTrackingManager(renderer, scene, camera, {
            enableHandModels: this.options.enableHandTracking,
            enableGestureRecognition: this.options.enableGestureRecognition,
            debugMode: true, // 启用调试模式以确保手部模型可见
            handModelStyle: 'mesh' // 使用网格模型
        });
        
        // 摄像头权限管理器
        this.cameraPermissionManager = new CameraPermissionManager();
        this.handTrackingEnabled = false;
        this.handTrackingSupported = false;
        
        // 音频权限管理器 - XR语音功能核心组件
        this.audioPermissionManager = new AudioPermissionManager();
        
        // 语音控制相关状态
        this._lastVoiceTriggerTime = null;
        this._lastReadyCheckTime = null;
        this._lastAudioResumeTime = null;
        
        // 保存实例到window，以便在语音合成错误处理时访问
        window._xrManager = this;
        
        // 交互系统
        this.interactableObjects = new Set();
        this.selectedObject = null;
        this.hoveredObject = null;
        this.raycastTargets = [];
        
        // 手势识别 - 统一使用HandTrackingManager
        // 移除重复的手势识别系统，避免冲突
        
        // 事件系统
        this.eventListeners = new Map();
        
        // 性能监控
        this.performanceStats = {
            frameRate: 0,
            renderTime: 0,
            lastFrameTime: 0
        };
        
        this.init();
    }
    
    /**
     * 绑定音频权限相关事件
     */
    bindAudioPermissionEvents() {
        // 监听音频权限授予事件
        this.audioPermissionManager.on('permissionGranted', () => {
            console.log('🎵 音频权限已授予，准备启动语音系统');
            this.triggerVoiceInputStart();
        });
        
        // 监听音频权限拒绝事件
        this.audioPermissionManager.on('permissionDenied', () => {
            console.log('⚠️ 用户拒绝了音频权限');
        });
        
        // 监听音频权限错误事件
        this.audioPermissionManager.on('permissionError', (data) => {
            console.error('❌ 音频权限请求错误:', data.error);
        });
    }
    
    async init() {
        console.log('🚀 初始化统一XR管理器...');
        
        try {
            // 启用WebXR
            if (this.renderer && this.renderer.xr) {
                this.renderer.xr.enabled = true;
            }
            
            // 检查WebXR支持
            await this.checkWebXRSupport();
            
            // 初始化手部追踪管理器
            if (this.options.enableHandTracking) {
                await this.handTrackingManager.init();
                this.handTrackingSupported = this.handTrackingManager.isSupported;
            }
            
            // 设置事件监听器
            this.setupEventListeners();
            
            // 绑定音频权限事件
            this.bindAudioPermissionEvents();
            
            // 初始化WebXRAudioSolution
            if (webXRAudioSolution && typeof webXRAudioSolution.init === 'function') {
                await webXRAudioSolution.init();
                console.log('✅ WebXR音频解决方案初始化完成');
            }
            
            // 确保window.app引用正确
            if (window.app) {
                console.log('✅ UnifiedXRManager已连接到应用实例');
                // 将音频权限管理器绑定到应用
                if (!window.app.audioPermissionManager) {
                    window.app.audioPermissionManager = this.audioPermissionManager;
                }
            } else {
                console.warn('⚠️ UnifiedXRManager未找到window.app引用');
            }
            
            console.log('✅ 统一XR管理器初始化完成');
        } catch (error) {
            console.error('❌ XR管理器初始化失败:', error);
        }
    }
    
    async checkWebXRSupport() {
        if (!navigator.xr) {
            throw new Error('WebXR不受支持');
        }

        // 检查VR/AR模式支持
        const vrSupported = await navigator.xr.isSessionSupported('immersive-vr');
        let arSupported = false;
        try {
            arSupported = await navigator.xr.isSessionSupported('immersive-ar');
        } catch (_) {
            arSupported = false;
        }
        console.log('VR支持:', vrSupported, 'AR支持:', arSupported);

        // 检查手部追踪能力（无需会话）
        const hasXRHand = 'XRHand' in window;
        const hasGetHand = !!(this.renderer && this.renderer.xr && typeof this.renderer.xr.getHand === 'function');
        this.handTrackingSupported = (hasXRHand || hasGetHand) && (vrSupported || arSupported);
        console.log('手部追踪支持:', this.handTrackingSupported);

        return { vrSupported, arSupported, handTrackingSupported: this.handTrackingSupported };
    }
    
    setupEventListeners() {
        // XR会话事件 - 统一处理
        this.renderer.xr.addEventListener('sessionstart', this.onXRSessionStart.bind(this));
        this.renderer.xr.addEventListener('sessionend', this.onXRSessionEnd.bind(this));
    }
    
    // 提取语音输入启动逻辑到单独方法，方便重用
    async triggerVoiceInputStart() {
        console.log('🎤 XR模式：开始语音输入');
        
        // 首先检查音频权限
        const hasPermission = this.audioPermissionManager.checkPermissionStatus();
        if (!hasPermission) {
            console.log('📢 需要音频权限，显示权限请求对话框');
            await this.audioPermissionManager.requestAudioPermission();
            return; // 权限请求会通过事件回调继续流程
        }
        
        // 确保音频上下文处于活动状态（WebXR关键修复）
        await this.resumeAudioContext();
        
        // 调用应用的语音管理器开始监听
        if (window.app?.voiceManager) {
            try {
                // 确保语音管理器已初始化
                if (!window.app.voiceManager.isInitialized) {
                    await window.app.voiceManager.init();
                }
                
                // 启动语音识别
                if (window.app.voiceManager.startListening) {
                    await window.app.voiceManager.startListening();
                }
                console.log('✅ XR模式语音输入已启动');
            } catch (error) {
                console.error('❌ XR模式启动语音输入失败:', error);
            }
        } else {
            console.warn('⚠️ 未找到应用的语音管理器');
        }
    }
    
    // 停止语音输入
    triggerVoiceInputStop() {
        console.log('🎤 XR模式：停止语音输入');
        
        if (window.app?.voiceManager) {
            try {
                if (window.app.voiceManager.stopListening) {
                    window.app.voiceManager.stopListening();
                }
                console.log('✅ XR模式语音输入已停止');
            } catch (error) {
                console.error('❌ XR模式停止语音输入失败:', error);
            }
        }
    }
    
    // 恢复音频上下文（关键修复）
    async resumeAudioContext() {
        const now = Date.now();
        // 频率限制，避免短时间内多次恢复
        if (this._lastAudioResumeTime && (now - this._lastAudioResumeTime < 500)) {
            console.warn('⏱️ 频率限制：忽略短时间内重复的音频上下文恢复请求');
            return;
        }
        this._lastAudioResumeTime = now;
        
        console.log('🔊 XR模式：尝试恢复音频上下文');
        
        try {
            // 1. 优先通过AudioPermissionManager恢复
            if (this.audioPermissionManager) {
                const success = await this.audioPermissionManager.ensureAudioContextRunning();
                if (success) {
                    console.log('✅ 通过AudioPermissionManager恢复音频上下文成功');
                    return true;
                }
            }
            
            // 2. 尝试通过VoiceManager恢复
            if (window.app?.voiceManager && window.app.voiceManager.ensureAudioActive) {
                const success = await window.app.voiceManager.ensureAudioActive();
                if (success) {
                    console.log('✅ 通过VoiceManager恢复音频上下文成功');
                    return true;
                }
            }
            
            // 3. 最后尝试直接恢复全局音频上下文（如果存在）
            if (window.app?.audioContext) {
                if (window.app.audioContext.state === 'suspended') {
                    await window.app.audioContext.resume();
                    console.log('✅ 直接恢复音频上下文成功');
                    return true;
                }
            }
            
            console.log('🔊 音频上下文已经处于活动状态');
            return true;
        } catch (error) {
            console.error('❌ 恢复音频上下文失败:', error);
            return false;
        }
    }
    
    // 检查WebXR会话是否准备好
    checkXRReady() {
        const now = Date.now();
        // 频率限制
        if (this._lastReadyCheckTime && (now - this._lastReadyCheckTime < 1000)) {
            return;
        }
        this._lastReadyCheckTime = now;
        
        // 检查会话状态并确保音频正常
        if (this.isXRActive) {
            this.resumeAudioContext().then(() => {
                // 如果语音识别未启动，尝试启动
                if (window.app?.voiceManager && !window.app.voiceManager.isListening) {
                    this.triggerVoiceInputStart();
                }
            });
        }
    }
    
    async onXRSessionStart(event) {
        console.log('🎯 XR会话开始');
        this.xrSession = this.renderer.xr.getSession();
        this.isXRActive = true;
        
        // 触发语音输入开始 - XR模式下的关键操作
        this.triggerVoiceInputStart();

        // 详细记录XR会话信息
        console.log('📊 XR会话详细信息:', {
            sessionMode: this.xrSession.mode,
            enabledFeatures: this.xrSession.enabledFeatures ? Array.from(this.xrSession.enabledFeatures) : 'N/A',
            visibilityState: this.xrSession.visibilityState,
            environmentBlendMode: this.xrSession.environmentBlendMode,
            supportedFrameRates: this.xrSession.supportedFrameRates || 'N/A'
        });

        // 监控输入源变化
        this.xrSession.addEventListener('inputsourceschange', (event) => {
            console.log('🔄 输入源变化事件:', {
                added: event.added ? event.added.length : 0,
                removed: event.removed ? event.removed.length : 0,
                totalInputSources: this.xrSession.inputSources ? this.xrSession.inputSources.length : 0
            });
            
            if (event.added && event.added.length > 0) {
                event.added.forEach((inputSource, index) => {
                    console.log(`➕ 新增输入源 ${index}:`, {
                        handedness: inputSource.handedness,
                        targetRayMode: inputSource.targetRayMode,
                        hasHand: !!inputSource.hand,
                        hasGamepad: !!inputSource.gamepad,
                        profiles: inputSource.profiles
                    });
                });
            }
        });

        // 设置参考空间为local-floor，增强手势与地面坐标的稳定性
        if (this.renderer && this.renderer.xr && typeof this.renderer.xr.setReferenceSpaceType === 'function') {
            this.renderer.xr.setReferenceSpaceType('local-floor');
        }

        // 检测设备类型
        await this.detectDeviceType();
        
        // 设置控制器
        this.setupControllers();
        
        // 启用手部追踪
        if (this.handTrackingSupported && this.options.enableHandTracking) {
            // Vision Pro特定检查
            if (this.deviceType === 'vision-pro') {
                console.log('🍎 Vision Pro设备检测到，检查手部追踪权限...');
                
                // 检查手部追踪特性是否在启用的特性中
                const handTrackingEnabled = this.xrSession.enabledFeatures && 
                    this.xrSession.enabledFeatures.has('hand-tracking');
                console.log('📋 hand-tracking特性状态:', handTrackingEnabled ? '✅ 已启用' : '❌ 未启用');
                
                if (!handTrackingEnabled) {
                    console.warn('⚠️ Vision Pro未启用hand-tracking特性，检查摄像头权限...');
                    
                    // 检查摄像头权限状态
                    const permissionStatus = await this.cameraPermissionManager.checkPermissionStatus();
                    console.log('📷 摄像头权限状态:', permissionStatus);
                    
                    if (permissionStatus !== 'granted') {
                        console.log('🔐 摄像头权限未授予，尝试请求权限...');
                        const permissionResult = await this.requestCameraPermissionWithRetry();
                        
                        if (!permissionResult.success) {
                            console.error('❌ 摄像头权限请求失败:', permissionResult.message);
                            this.cameraPermissionManager.showPermissionGuide();
                            return; // 不继续启用手部追踪
                        }
                    }
                }
            }
            
            await this.handTrackingManager.enable(this.xrSession);
            this.handTrackingEnabled = this.handTrackingManager.isEnabled;
            
            // 添加定期检查输入源的机制
            this.startInputSourceMonitoring();
        }
        
        // 启用手势识别
        if (this.options.enableGestureRecognition) {
            this.handTrackingManager.stopGestureRecognition();
        }
        
        // 触发全局事件
        window.dispatchEvent(new CustomEvent('webxr:xrstart', { detail: { session: this.xrSession } }));
        
        // 触发自定义事件，用于WebXRAudioSolution监听
        if (typeof this.dispatchEvent === 'function') {
            this.dispatchEvent('xr-session-start', { session: this.xrSession });
        } else {
            console.warn('⚠️ dispatchEvent方法不存在');
        }
        
        console.log('✅ XR会话设置完成');
    }
    
    onXRSessionEnd(event) {
        console.log('🔚 XR会话结束');
        this.isXRActive = false;
        
        // 不要完全停止语音输入，而是让其保持在准备状态
        // 这样在XR会话结束后，用户仍然可以继续对话
        if (window.app && window.app.voiceManager) {
            // 只在语音管理器确实在监听时才进行处理
            if (window.app.voiceManager.isListening) {
                console.log('✅ XR会话结束：语音系统保持准备状态');
                // 不调用stopListening，让语音系统保持活跃
            }
        }
        
        // 停止输入源监控
        this.stopInputSourceMonitoring();
        
        // 禁用手部追踪
        if (this.handTrackingEnabled) {
            this.handTrackingManager.disable();
            this.handTrackingEnabled = false;
        }
        
        // 清理控制器
        this.cleanupControllers();
        
        // 停止手势识别
        this.stopGestureRecognition();
        
        // 重置状态
        this.xrSession = null;
        this.xrMode = null;
        this.deviceType = null;
        
        // 触发全局事件
        window.dispatchEvent(new CustomEvent('webxr:xrend', { detail: { session: event.session } }));
        
        // 触发自定义事件，用于WebXRAudioSolution监听
        if (typeof this.dispatchEvent === 'function') {
            this.dispatchEvent('xr-session-end');
        } else {
            console.warn('⚠️ dispatchEvent方法不存在');
        }
        
        // 添加：确保事件监听器完整性，防止监听器缺失
        this.ensureEventListeners();
    }
    
    // 确保事件监听器完整性的方法
    ensureEventListeners() {
        console.log('🔍 确保XR事件监听器完整性');
        // 检查并重新添加必要的事件监听器，防止监听器在某些情况下丢失
        if (this.renderer && this.renderer.xr) {
            // 移除可能重复的监听器，然后重新添加
            this.renderer.xr.removeEventListener('sessionstart', this.onXRSessionStart.bind(this));
            this.renderer.xr.removeEventListener('sessionend', this.onXRSessionEnd.bind(this));
            this.renderer.xr.addEventListener('sessionstart', this.onXRSessionStart.bind(this));
            this.renderer.xr.addEventListener('sessionend', this.onXRSessionEnd.bind(this));
            console.log('✅ XR事件监听器已重新添加');
        }
    }
    
    async detectDeviceType() {
        // 简化的设备检测逻辑
        const userAgent = navigator.userAgent.toLowerCase();
        if (userAgent.includes('vision')) {
            this.deviceType = 'vision-pro';
        } else if (userAgent.includes('quest')) {
            this.deviceType = 'quest';
        } else {
            this.deviceType = 'generic';
        }
        
        console.log('检测到设备类型:', this.deviceType);
    }
    
    setupControllers() {
        // 清理现有控制器
        this.cleanupControllers();
        
        // 设置左右控制器
        for (let i = 0; i < 2; i++) {
            const controller = this.renderer.xr.getController(i);
            const controllerGrip = this.renderer.xr.getControllerGrip(i);
            
            // 添加事件监听器
            controller.addEventListener('selectstart', (event) => this.onControllerSelectStart(event, i));
            controller.addEventListener('selectend', (event) => this.onControllerSelectEnd(event, i));
            controller.addEventListener('squeezestart', (event) => this.onControllerSqueezeStart(event, i));
            controller.addEventListener('squeezeend', (event) => this.onControllerSqueezeEnd(event, i));
            
            // 添加控制器模型
            const controllerModel = this.controllerModelFactory.createControllerModel(controller);
            controllerGrip.add(controllerModel);
            
            // 添加到场景
            this.scene.add(controller);
            this.scene.add(controllerGrip);
            
            // 存储引用
            this.controllers.push(controller);
            this.controllerGrips.push(controllerGrip);
        }
    }
    
    // 统一的射线检测方法
    performRaycast(origin, direction, targets = null) {
        const raycaster = new THREE.Raycaster(origin, direction);
        const targetObjects = targets || Array.from(this.interactableObjects);
        return raycaster.intersectObjects(targetObjects, true);
    }
    
    // 统一的对象选择方法
    selectObject(object, source = 'unknown') {
        if (this.selectedObject === object) return;
        
        // 取消之前的选择
        if (this.selectedObject) {
            this.deselectObject(this.selectedObject);
        }
        
        this.selectedObject = object;
        
        // 触发选择事件
        this.dispatchEvent('object-selected', { 
            object, 
            source,
            timestamp: Date.now() 
        });
        
        console.log('对象已选择:', object, '来源:', source);
    }
    
    deselectObject(object) {
        if (this.selectedObject === object) {
            this.selectedObject = null;
        }
        
        // 触发取消选择事件
        this.dispatchEvent('object-deselected', { 
            object,
            timestamp: Date.now() 
        });
    }
    
    // 控制器事件处理
    onControllerSelectStart(event, controllerIndex) {
        const handedness = controllerIndex === 0 ? 'left' : 'right';
        const controller = this.controllers[controllerIndex];
        
        if (!controller) return;
        
        // 获取控制器位置和方向
        const position = new THREE.Vector3();
        const direction = new THREE.Vector3(0, 0, -1);
        
        controller.getWorldPosition(position);
        controller.getWorldDirection(direction);
        
        // 执行射线检测
        const intersects = this.performRaycast(position, direction);
        
        if (intersects.length > 0) {
            this.selectObject(intersects[0].object, `controller-${handedness}`);
        }
        
        // 触发控制器选择事件
        this.dispatchEvent('controller-select-start', {
            controllerIndex,
            handedness,
            position: position.clone(),
            direction: direction.clone()
        });
    }
    
    onControllerSelectEnd(event, controllerIndex) {
        const handedness = controllerIndex === 0 ? 'left' : 'right';
        
        this.dispatchEvent('controller-select-end', {
            controllerIndex,
            handedness
        });
    }
    
    onControllerSqueezeStart(event, controllerIndex) {
        const handedness = controllerIndex === 0 ? 'left' : 'right';
        
        this.dispatchEvent('controller-squeeze-start', {
            controllerIndex,
            handedness
        });
    }
    
    onControllerSqueezeEnd(event, controllerIndex) {
        const handedness = controllerIndex === 0 ? 'left' : 'right';
        
        this.dispatchEvent('controller-squeeze-end', {
            controllerIndex,
            handedness
        });
    }
    
    // 手势识别统一由HandTrackingManager处理
    // 移除重复的手势识别方法，避免冲突
    
    startGestureRecognition() {
        console.log('🎯 开始手势识别');
        if (this.handTrackingManager) {
            this.handTrackingManager.startGestureRecognition();
        }
    }
    
    stopGestureRecognition() {
        console.log('🛑 停止手势识别');
        if (this.handTrackingManager) {
            this.handTrackingManager.stopGestureRecognition();
        }
    }
    
    /**
     * 开始输入源监控
     */
    startInputSourceMonitoring() {
        if (this.inputSourceMonitorInterval) {
            clearInterval(this.inputSourceMonitorInterval);
        }
        
        let lastInputSourceCount = 0;
        let noInputSourceWarningShown = false;
        
        this.inputSourceMonitorInterval = setInterval(() => {
            if (!this.xrSession || !this.xrSession.inputSources) return;
            
            const currentCount = this.xrSession.inputSources.length;
            
            // 如果输入源数量发生变化，记录详细信息
            if (currentCount !== lastInputSourceCount) {
                console.log(`🔄 输入源数量变化: ${lastInputSourceCount} → ${currentCount}`);
                lastInputSourceCount = currentCount;
                noInputSourceWarningShown = false;
            }
            
            // 如果没有输入源且未显示过警告
            if (currentCount === 0 && !noInputSourceWarningShown) {
                console.warn('⚠️ 未检测到任何输入源');
                console.log('💡 Vision Pro手部追踪提示：');
                console.log('   • 确保双手在设备视野范围内');
                console.log('   • 检查光照条件是否充足');
                console.log('   • 尝试移动双手或做手势动作');
                console.log('   • 确认已授权摄像头权限');
                noInputSourceWarningShown = true;
            }
            
            // 记录当前输入源状态（每30秒一次）
            if (Date.now() % 30000 < 2000) {
                this.logInputSourceStatus();
            }
        }, 2000); // 每2秒检查一次
    }
    
    /**
     * 停止输入源监控
     */
    stopInputSourceMonitoring() {
        if (this.inputSourceMonitorInterval) {
            clearInterval(this.inputSourceMonitorInterval);
            this.inputSourceMonitorInterval = null;
        }
    }
    
    /**
     * 记录输入源状态
     */
    logInputSourceStatus() {
        if (!this.xrSession || !this.xrSession.inputSources) {
            console.log('📊 输入源状态: 无XR会话或输入源');
            return;
        }
        
        const inputSources = this.xrSession.inputSources;
        console.log(`📊 当前输入源状态 (${inputSources.length}个):`);
        
        if (inputSources.length === 0) {
            console.log('   • 无输入源检测到');
        } else {
            Array.from(inputSources).forEach((source, index) => {
                console.log(`   • 输入源 ${index}: ${source.handedness} ${source.targetRayMode}`, {
                    hasHand: !!source.hand,
                    hasGamepad: !!source.gamepad,
                    profiles: source.profiles
                });
            });
        }
    }
    
    /**
     * 带重试的摄像头权限请求
     */
    async requestCameraPermissionWithRetry(maxRetries = 3) {
        for (let attempt = 1; attempt <= maxRetries; attempt++) {
            console.log(`🔄 摄像头权限请求尝试 ${attempt}/${maxRetries}`);
            
            const result = await this.cameraPermissionManager.requestCameraPermission();
            
            if (result.success) {
                console.log('✅ 摄像头权限请求成功');
                return result;
            }
            
            console.warn(`❌ 第${attempt}次权限请求失败:`, result.message);
            
            // 如果是用户拒绝或安全错误，不再重试
            if (result.status === 'denied' || result.status === 'security_error') {
                break;
            }
            
            // 等待一段时间后重试
            if (attempt < maxRetries) {
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
        }
        
        return {
            success: false,
            status: 'failed_after_retries',
            message: `经过${maxRetries}次尝试后仍无法获取摄像头权限`
        };
    }
    
    /**
     * 检查并请求必要的权限
     */
    async checkAndRequestPermissions() {
        console.log('🔍 检查必要权限...');
        
        // 检查摄像头权限
        const cameraStatus = await this.cameraPermissionManager.checkPermissionStatus();
        console.log('📷 摄像头权限状态:', cameraStatus);
        
        if (cameraStatus !== 'granted') {
            console.log('🔐 需要请求摄像头权限');
            const result = await this.requestCameraPermissionWithRetry();
            
            if (!result.success) {
                return {
                    success: false,
                    missingPermissions: ['camera'],
                    message: '摄像头权限未授予'
                };
            }
        }
        
        return {
            success: true,
            message: '所有必要权限已获得'
        };
    }
    
    /**
     * 主要更新方法 - 每帧调用
     * @param {number} delta - 时间增量
     * @param {number} time - 当前时间
     * @param {XRFrame} frame - XR帧对象
     */
    update(delta, time, frame) {
        if (!this.isXRActive || !this.xrSession) {
            return;
        }
        
        try {
            // 更新控制器状态
            this.updateControllers(frame);
            
            // 更新手部追踪
            if (this.handTrackingEnabled && this.handTrackingManager) {
                this.handTrackingManager.update(frame, delta);
                
                // 每5秒输出一次手部追踪状态（调试用）
                if (Math.floor(time / 5000) !== Math.floor((time - delta * 1000) / 5000)) {
                    console.log('🤲 手部追踪状态:', {
                        enabled: this.handTrackingEnabled,
                        hasLeftController: !!this.handTrackingManager.hands?.left?.controller,
                        hasRightController: !!this.handTrackingManager.hands?.right?.controller,
                        hasLeftModel: !!this.handTrackingManager.hands?.left?.model,
                        hasRightModel: !!this.handTrackingManager.hands?.right?.model,
                        leftModelVisible: this.handTrackingManager.hands?.left?.model?.visible,
                        rightModelVisible: this.handTrackingManager.hands?.right?.model?.visible,
                        inputSources: this.xrSession.inputSources.length
                    });
                }
            }
            
            // 更新交互检测
            this.updateInteractions(delta);
            
            // 手势识别的更新由 HandTrackingManager.update 内部驱动

        } catch (error) {
            console.warn('XR更新过程中出现错误:', error);
        }
    }
    
    /**
     * 更新控制器状态
     * @param {XRFrame} frame - XR帧对象
     */
    updateControllers(frame) {
        if (!frame || !this.controllers) return;
        
        this.controllers.forEach((controller, index) => {
            if (controller && controller.visible) {
                // 控制器已经由Three.js自动更新位置
                // 这里可以添加额外的控制器逻辑
            }
        });
    }
    

    
    /**
     * 更新交互检测
     * @param {number} delta - 时间增量
     */
    updateInteractions(delta) {
        // 更新射线检测
        this.updateRaycast();
        
        // 更新选中对象状态
        if (this.selectedObject) {
            // 可以在这里添加选中对象的动画或效果
        }
    }
    
    /**
     * 更新射线检测
     */
    updateRaycast() {
        if (!this.controllers || this.controllers.length === 0) return;
        
        this.controllers.forEach((controller, index) => {
            if (controller && controller.visible) {
                // 执行射线检测
                const tempMatrix = new THREE.Matrix4();
                tempMatrix.identity().extractRotation(controller.matrixWorld);
                
                const raycaster = new THREE.Raycaster();
                raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld);
                raycaster.ray.direction.set(0, 0, -1).applyMatrix4(tempMatrix);
                
                // 检测交互对象
                if (this.raycastTargets.length > 0) {
                    const intersects = raycaster.intersectObjects(this.raycastTargets, true);
                    
                    if (intersects.length > 0) {
                        const intersectedObject = intersects[0].object;
                        if (this.hoveredObject !== intersectedObject) {
                            // 处理悬停状态变化
                            if (this.hoveredObject) {
                                this.dispatchEvent('object-hover-end', { object: this.hoveredObject });
                            }
                            this.hoveredObject = intersectedObject;
                            this.dispatchEvent('object-hover-start', { object: intersectedObject });
                        }
                    } else if (this.hoveredObject) {
                        this.dispatchEvent('object-hover-end', { object: this.hoveredObject });
                        this.hoveredObject = null;
                    }
                }
            }
        });
    }
    
    // 清理方法
    cleanupControllers() {
        this.controllers.forEach(controller => {
            if (controller.parent) {
                controller.parent.remove(controller);
            }
        });
        
        this.controllerGrips.forEach(grip => {
            if (grip.parent) {
                grip.parent.remove(grip);
            }
        });
        
        this.controllers = [];
        this.controllerGrips = [];
    }
    

    
    // 事件系统
    addEventListener(eventType, callback) {
        if (!this.eventListeners.has(eventType)) {
            this.eventListeners.set(eventType, []);
        }
        this.eventListeners.get(eventType).push(callback);
    }
    
    removeEventListener(eventType, callback) {
        if (this.eventListeners.has(eventType)) {
            const callbacks = this.eventListeners.get(eventType);
            const index = callbacks.indexOf(callback);
            if (index > -1) {
                callbacks.splice(index, 1);
            }
        }
    }
    
    dispatchEvent(eventType, data = {}) {
        if (this.eventListeners.has(eventType)) {
            this.eventListeners.get(eventType).forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`事件处理器错误 (${eventType}):`, error);
                }
            });
        }
    }
    
    // 注册交互对象
    registerInteractableObject(object, metadata = {}) {
        this.interactableObjects.add(object);
        
        // 可以在对象上存储元数据
        if (metadata) {
            object.userData.interactionMetadata = metadata;
        }
    }
    
    unregisterInteractableObject(object) {
        this.interactableObjects.delete(object);
    }
    
    // 获取当前状态
    getXRState() {
        return {
            isActive: this.isXRActive,
            session: this.xrSession,
            mode: this.xrMode,
            deviceType: this.deviceType,
            handTrackingEnabled: this.handTrackingEnabled,
            controllersCount: this.controllers.length
        };
    }
    
    // 清理资源
    dispose() {
        console.log('🧹 清理统一XR管理器');
        
        // 停止输入源监控
        this.stopInputSourceMonitoring();
        
        // 停止手势识别
        this.stopGestureRecognition();
        
        // 清理手部追踪
        if (this.handTrackingManager) {
            this.handTrackingManager.dispose();
        }
        
        // 清理摄像头权限管理器
        if (this.cameraPermissionManager) {
            this.cameraPermissionManager.dispose();
        }
        
        // 清理控制器
        this.cleanupControllers();
        
        // 清理事件监听器
        this.eventListeners.clear();
        
        // 重置状态
        this.isXRActive = false;
        this.xrSession = null;
        this.handTrackingEnabled = false;
        this.interactableObjects.clear();
    }
}